package com.xiaobai;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Marry {
    void smileMarry();
}

public class JDKProxy {
    public static void main(String[] args) {
        Marry proxy = (Marry) new MyInvocationHandler().getJDKProxy(new MyMarry());
        proxy.smileMarry();
        System.out.println();
        Marry proxy1 = (Marry) new MyInvocationHandler().getJDKProxy(new MySonMarry());
        proxy1.smileMarry();

        try {
            Thread.sleep(2000000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class MyMarry implements Marry {
    @Override
    public void smileMarry() {
        System.out.println("笑着结婚中");
    }
}

class MySonMarry implements Marry {
    @Override
    public void smileMarry() {
        System.out.println("儿子笑着结婚中");
    }
}

class MyInvocationHandler implements InvocationHandler {
    private Object target;

    /**
     * 获取代理对象
     *
     * @param target 被代理的对象
     * @return 代理对象
     */
    public Object getJDKProxy(Object target) {
        this.target = target;
        // loader：ClassLoader对象，定义哪个ClassLoader对象加载生成代理对象
        // interfaces：一个Interface对象的数组，即给代理的对象提供一组接口，代理对象就会实现了这些接口(多态)，这样我们就能调用这些接口中的方法
        // h：:InvocationHandler对象，当动态代理对象在调用方法的时候，会调用InvocationHandler对象的invoke方法
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object res = method.invoke(target, args);
        after();
        return res;
    }

    public void before() {
        System.out.println("接新娘");
    }

    public void after() {
        System.out.println("入洞房");
    }
}
